package com.pi.smart.base.task;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.pi.base.concurrent.BaseExecutors;
import com.pi.base.enumerate.redis.RedisCacheEnum;
import com.pi.base.util.cache.RedisUtil;
import com.pi.smart.client.ins.comm.annotation.ForLogIns;
import com.pi.smart.client.ins.comm.category.SmartInsEnum;
import com.pi.smart.client.ins.comm.domain.BaseInsMessage;
import com.pi.smart.client.ins.comm.variety.LogInsHandler;

/**
 * @description 记录睡眠日志
 * @author chenmfa
 */
@Component
public class DcCmdLogTask {
  private static final Logger logger = LoggerFactory.getLogger(DcCmdLogTask.class);

  private static volatile boolean isRunning = true;
  
  @Autowired
  private List<LogInsHandler> logInsHandlers;

  private static Map<SmartInsEnum, LogInsHandler> insLogTaskHandlerMap = new ConcurrentHashMap<>();
  
  @PostConstruct
  public void initDataLogger(){
    logger.info("[logger-RECORDER]开始启动全局日志记录器：{}", System.currentTimeMillis());
    preProcessLogTask();
    BaseExecutors.executor.submit(() -> {
      while(isRunning){
        try {
          readLog();
        }catch(Exception e) {
          logger.error("处理睡眠指令失败", e);
        }
      }
    });
  }
  private void readLog(){
    BaseInsMessage cmdLog = null;
      try {
        cmdLog = RedisUtil.blpop(RedisCacheEnum.SMART_DEVICE_CMD_COMMON);
      } catch (ClassNotFoundException | IOException e) {
        logger.error("获取指令记录失败：", e);
        return;
      }
      if(null == cmdLog){
        try {Thread.sleep(3000);} catch (InterruptedException e){}
        return;
      }else{
        logger.info("[DEV_INS_SCAN]查询设备指令数据- {}", cmdLog);
      }
      //
      if(insLogTaskHandlerMap.containsKey(SmartInsEnum.SMART_BED)){
        insLogTaskHandlerMap.get(SmartInsEnum.SMART_BED).handle(cmdLog);
      }else{
        logger.error("未定义的指令：{}", cmdLog);
      }
  }
  
  private void preProcessLogTask(){
    if(null == logInsHandlers){
      return;
    }
    for(LogInsHandler logInsHandler : logInsHandlers){
      ForLogIns annotation = logInsHandler.getClass().getAnnotation(ForLogIns.class);
      if(null != annotation){
        insLogTaskHandlerMap.putIfAbsent(annotation.ins(), logInsHandler);
      }
    }
  }
  
  public static void shutdownTask(){
    isRunning = false;
  }
}
